import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/material.dart';

import '../../utils/default/Empty.dart';
import '../../widget/icon_text.dart';
import '../../widget/photo_view.dart';

class ProfileMoment extends StatefulWidget {

  String memberId;

  ProfileMoment({Key? key, required this.memberId}) : super(key: key);

  @override
  State<ProfileMoment> createState() => _ProfileMomentState();
}

class _ProfileMomentState extends State<ProfileMoment> {
  late double _screenWidth;
  int pageNo = 1;
  bool isLoading = false;
  final _listData = <dynamic>[];
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();

    _getData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });

  }

  _getData() async {
    final res = await Api.getInstance().getMoodList(widget.memberId,pageNo,10);
    final data = res['data']['list'];

    if (data != null) {
      List list = data;
      if (list.isNotEmpty) {
        _listData.clear();
        setState(() {
          _listData.addAll(list);
        });
      }
    }
  }

  /// 下拉刷新方法,为list重新赋值
  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 3), () {});
  }

  /// 上拉加载更多
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(const Duration(seconds: 1), () {});
    }
  }

  Widget _getMoreWidget() {
    return Center(
      child: Offstage(
        offstage: !isLoading,
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return  _listData.isEmpty ? const Empty() : ListView.builder(
      controller: _scrollController,
      itemCount: _listData.length,
      itemBuilder: (ctx, index) {
        if (index == _listData.length) {
          //加载更多
          return _getMoreWidget();
        } else {
          if (_listData?.isNotEmpty == true) {
            return Container(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildDate(_listData?[index]),
                  Container(
                    padding: const EdgeInsets.only(left: 28, top: 12),
                    child: Text(
                      _listData?[index]['content'],
                      style: TextStyle(color: ThemeColor.textColor, fontSize: 12),
                    ),
                  ),
                  _buildPhoto(_listData[index]),
                  const SizedBox(
                    height: 12,
                  ),
                  _buildActions(_listData[index]['likeCount'], _listData[index]['commentCount'])
                ],
              ),
            );
          } else {
            return Container();
          }
        }

      },
    );
  }

  /// 日期、地址、内容
  Widget _buildDate(itemData) {
    String str = itemData['createTime'].toString();
    String day = str.substring(8,10);
    String month = str.substring(6,7);
    print(str);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text.rich(TextSpan(children: [
          TextSpan(
              text: day,
              style: TextStyle(color: ThemeColor.textColor, fontSize: 24)),
          TextSpan(
              text: '$month月',
              style: TextStyle(color: ThemeColor.textColor, fontSize: 12))
        ])),

        const SizedBox(width: 5,),
        // Text.rich(
        //   TextSpan(
        //
        //     style: TextStyle(fontSize: 12,color: Colors.grey),
        //     children: [
        //
        //       WidgetSpan(
        //         child: Image.asset('images/ic_path.png',width: 13,height: 13,color: Colors.grey,),
        //       ),
        //
        //       const TextSpan(
        //         text: ' 北京',
        //       ),
        //
        //     ],
        //   ),
        // ),

    ],
    );
  }

  /// 照片集合
  Widget _buildPhoto(itemData) {
    final urls = itemData['picUrls'];
    List<String> photos = urls == null || urls.isEmpty ? <String>[] : urls.split(',');
    photos.removeWhere((element) => element.isEmpty);

    if (photos.isEmpty) {
      return const SizedBox(
        width: 0,
        height: 0,
      );
    }
    if (photos.length == 1) {
      double width = _screenWidth - 76;
      double height = (_screenWidth - 76) / 298 * 204;
      return Container(
          margin: const EdgeInsets.only(top: 12,left: 28,),
          child: _buildPhotoView(photos[0],photos, Size(width, height)));
    }
    if (photos.length == 2) {
      double size = (_screenWidth - 82) / 2;
      return Container(
        margin: const EdgeInsets.only(top: 12,left: 28),
        child: Row(
          children: [
            _buildPhotoView(photos[0],photos, Size(size, size)),
            const SizedBox(
              width: 6,
            ),
            _buildPhotoView(photos[1],photos,Size(size, size)),
          ],
        ),
      );
    }
    double firSize = (_screenWidth - 82) / 73 * 49;
    double secSize = (firSize - 6) / 2;
    return Container(
      padding: const EdgeInsets.fromLTRB(28, 12, 24, 0),
      height: firSize + 12,
      child: Stack(
        children: [
          Align(
              alignment: Alignment.topLeft,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: _buildPhotoView(photos[0],photos, Size(firSize, firSize)))),
          Align(
              alignment: Alignment.topRight,
              child: _buildPhotoView(photos[1],photos, Size(secSize, secSize))),
          Align(
              alignment: Alignment.bottomRight,
              child: _buildPhotoView(photos[2],photos, Size(secSize, secSize))),
          photos.length > 3
              ? _buildPhotoCountTag(photos.length)
              : const SizedBox(
                  width: 0,
                  height: 0,
                )
        ],
      ),
    );
  }

  Widget _getErrorBuilder(double width, double height) {
    return Container(
      width: width,
      height: height,
      decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(4)
          ),
          color: const Color(0xFFF2F2F2)
      ),
      alignment: Alignment.center,
      child: Image.asset(
        "images/ic_error_place.png",
        width: width * 0.5,
        height: height * 0.5,
      ) ,
    );
  }


  Widget _buildPhotoView(String url,List urls, Size size) {
    // final urls = [imageUrl, imageUrl, imageUrl];
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => PhotoPreview(
                      galleryItems: urls,
                      defaultImage: 0,
                    )
            )
        );
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Image.network(
          url,
          width: size.width,
          height: size.height,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  /// 照片数量标签
  Widget _buildPhotoCountTag(int count) {
    return Positioned(
      bottom: 6,
      right: 6,
      child: Container(
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
          color: Colors.black,
        ),
        height: 18,
        padding: const EdgeInsets.symmetric(horizontal: 4),
        alignment: Alignment.center,
        child: IconText(
          "  $count张",
          icon: const Icon(
            Icons.photo_library,
            size: 10,
            color: Colors.white,
          ),
          style: const TextStyle(fontSize: 10, color: Colors.white),
        ),
      ),
    );
  }

  /// 点赞 评论
  Widget _buildActions(int likeCount, int commentCount) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Expanded(child: Container()),
        const SizedBox(
          width: 28,
        ),
        IconText(
          "  $likeCount",
          icon: Icon(
            Icons.favorite, //favorite_outline
            color: ThemeColor.mainColor,
            size: 18,
          ),
          style: TextStyle(
            color: ThemeColor.textColorSecond,
            fontSize: 13,
          ),
        ),
        const SizedBox(
          width: 10,
        ),
        // IconText(
        //   "  $commentCount",
        //   style: TextStyle(
        //     color: ThemeColor.textColorSecond,
        //     fontSize: 13,
        //   ),
        //   icon: Icon(
        //     Icons.comment_outlined,
        //     color: ThemeColor.textColorSecond,
        //     size: 18,
        //   ),
        // )
      ],
    );
  }


}
